package com.kaifamiao.preventrefresh;

import com.alibaba.fastjson.JSON;
import com.kaifamiao.util.IPUtil;
import com.kaifamiao.util.ResultT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Component
public class PreventRefreshInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入拦截器");
        //判断请求是否属于方法的请求
        if(handler instanceof HandlerMethod){
            System.out.println("判断请求是否属于方法的请求");
            HandlerMethod hm = (HandlerMethod) handler;
            //获取方法中的注解,看是否有该注解
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if(accessLimit == null){
                return true;
            }
            //@AccessLimit(seconds=5, maxCount=5, needLogin=true)
            int minutes = accessLimit.minutes();
            int maxCount = accessLimit.maxCount();
            boolean login = accessLimit.needLogin();
            Map<String, Object> mp=new HashMap<>();
            mp.put("seconds",minutes);
            mp.put("maxCount",maxCount);
            mp.put("login",login);
            System.out.println(mp);
            String key = IPUtil.getIpAddr(request)+"_"+request.getRequestURI();
            log.error("Key:{}",key);
            //如果需要登录
//            if(login){
//                redisService.set(key, "1");
//            }
            //从redis中获取用户访问的次数
            String value = redisService.get(key);
            System.out.println("value:"+value);
            //判断value是否为null
            if(value == null){
                System.out.println("第1次访问，设置有效期"+minutes +"分钟");
                redisService.set(key, "1",minutes);
            }else{
                Long count = redisService.incr(key);
                System.out.println("第"+count+"次访问，设置有效期"+minutes +"分钟");
                System.out.println("{count :"+count + ", maxCount :"+maxCount+"}");
                if(count.intValue() > maxCount){
                    System.out.println("超出访问次数");
                    redisService.set(key, "999");
                    renderError(response);
                }
            }
        }

        return true;

    }
    private void renderError(HttpServletResponse response)throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        String str  = JSON.toJSONString(ResultT.error("250","超出访问次数"));
        out.write(str.getBytes("UTF-8"));
        out.flush();
        out.close();

    }
}